using System;
using Science.Mathematics;
using L=Science.Physics.GeneralPhysics;

namespace Serway.Chapter23
{
	/// <summary>
	/// Example03: Where is the Resultant Force Zero?
	/// Three point charges lie along the x axis as shown in Figure.
	/// The positive charge q_1 = 15.0 \mu C is at x = 2.0 m,
	/// the positive charge q_2 = 6 \mu C is at the origin, and
	/// the resultant force action on q_3 is zero. What is the
	/// x coordinate of q_3?
	/// x = 0.775 m	
	/// </summary>
	public class Example03
	{
		public Example03()
		{
		}
		private string result;
		public string Result
		{
			get{return result;}
		}
		public void Compute()
		{
			Function.DoubleAToDouble f 
				= new Function.DoubleAToDouble(func);
			Science.Mathematics.Calculus.Minimization obj = new Science.Mathematics.Calculus.Minimization(f);
			obj.NumberOfVariables = 2;
			double[] x = {0.1,2.0};  // one-dim did not work.
			obj.CenterOfInitialSimplex = x;
			obj.SizeOfInitialSimplex = 0.5;
			obj.Compute();
            result+=Convert.ToString(obj.MinimumAT[0])+"\r\n";
			result+=Convert.ToString(obj.MinimumValue)+"\r\n";
		}

		private double func(double[] x)
		{
			L.ElectricCharge q1 = new L.ElectricCharge();
			q1.C = 15.0E-6;
			L.ElectricCharge q2 = new L.ElectricCharge();
			q2.C = 6.0E-6;
			L.ElectricCharge q3 = new L.ElectricCharge();
			q3.C = 1.0;
			
			L.Position r1 = new L.Position();
			r1.X = 2.0;
			L.Position r2 = new L.Position();
			L.Position r3 = new L.Position();
			r3.X = x[0];
		
			L.ElectricForce F3by1 = new L.ElectricForce(q1,r1,q3,r3);
			L.ElectricForce F3by2 = new L.ElectricForce(q2,r2,q3,r3);
			L.Vector f = F3by1 + F3by2;
			return f.Norm + x[1]*x[1];
		}
	}
}
